<template>
  <div class="app-container">
    <!-- 头部过滤 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="height: 32px;line-height: 32px;">筛选条件</span>
      </div>
      <div style="marginTop:20px" class="filter-container">
        <el-form :model="formData" class="demo-form-inline">
          <el-form-item label="订单状态" label-width="68px">
            <el-radio-group v-model="formData.orderState" size="small">
              <el-radio-button v-for="item in orderStateOptions" :key="item.keyValue" :label="item.keyValue">{{item.caption}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="订单编号" label-width="68px">
            <el-input v-model="formData.orderId" clearable placeholder="订单编号" style="width:400px" size="small" />
          </el-form-item>
          <el-form-item label="时间选择" label-width="68px">
            <el-date-picker v-model="formData.dateTime" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" size="small" />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleSubmit" type="primary" size="medium">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格主体 -->
    <el-card style="marginTop:20px" class="box-card">
      <div slot="header" class="clearfix">
        <span>订单数据</span>
      </div>
      <div class="table-wrapper">
        <el-table height="60vh" :data="tableData" style="width: 100%">
          <el-table-column prop="order" width="120" label="序号" />
          <el-table-column prop="orderId" width="200" label="订单编号" />
          <el-table-column prop="orderAmount" width="120" label="订单金额" />
          <el-table-column prop="deliveryFee" width="120" label="运费" />
          <el-table-column prop="deliveryFee" width="120" label="配送地址" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.addressDTO | addressInfoFilter()}}</template>
          </el-table-column>
          <el-table-column prop="customerId" width="120" label="客户信息" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.addressDTO | customerInfoFilter()}}</template>
          </el-table-column>
          <el-table-column prop="orderStatus" width="240" label="订单状态">
            <template slot-scope="scope">{{ scope.row.orderStatus | orderStateFilter(orderStateOptions) }}</template>
          </el-table-column>
          <el-table-column prop="productCounts" label="总计数量" />
          <el-table-column width="200" label="创建日期">
            <template slot-scope="scope">{{ scope.row.createTime | timeFilter }}</template>
          </el-table-column>
          <el-table-column width="200" label="更新日期">
            <template slot-scope="scope">{{ scope.row.updateTime | timeFilter }}</template>
          </el-table-column>
          <el-table-column prop="remark" width="120" label="用户备注" show-overflow-tooltip />
          <el-table-column fixed="right" prop="state" width="250" label="操作">
            <template slot-scope="{row}">
              <el-button @click="handleModify(row)" type="text" v-if="row.btnModify">修改订单</el-button>
              <el-button @click="handleCancel(row)" type="text" v-if="row.btnCancel">取消订单</el-button>
              <el-button @click="handleSend(row)" type="text" v-if="row.btnDelivery">安排配送</el-button>
              <el-button @click="handleConfirmRefund(row)" type="text" v-if="row.btnReundAgree">退款/货确认</el-button>
              <el-button @click="handleConfirmRemind(row)" type="text" v-if="row.btnConfirmRemind">知晓提醒</el-button>
              <el-button @click="handleGoodsTaked(row)" type="text" v-if="row.btnGoodsTaked">货已自取</el-button>
              <el-button @click="handleExpress(row)" type="text" v-if="row.btnExpress">物流信息</el-button>
            </template>
          </el-table-column>
          <el-table-column fixed="right" type="expand" width="50" label="展开">
            <template slot-scope="props">
              <el-table :border="true" :data="props.row.items" style="width:100%">
                <el-table-column prop="productItemName" label="商品名称"></el-table-column>
                <el-table-column prop="productItemPrice" width="150" label="商品金额"></el-table-column>
                <el-table-column prop="productItemNum" width="150" label="商品数量"></el-table-column>
                <el-table-column label="商品规格">
                  <template slot-scope="scope">
                    <div v-for="item in scope.row.productItemSpecDTOS" :key="item.id" class="properties-item">
                      {{ item.specificationName }}：{{ item.propertyName }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="290" label="缩略图">
                  <template slot-scope="scope">
                    <img width="64" height="64" :src="scope.row.productItemPic" alt="">
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div style="marginTop:30px;textAlign: center;" class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
        </el-pagination>
      </div>
    </el-card>

    <!-- 修改订单 -->
    <el-dialog title="修改订单" v-if="dialogOrderVisible" :visible.sync="dialogOrderVisible" width="80%">
      <el-divider />
      <el-form v-if="orderForm.orderId" :inline="false" label-width="100px" :model="orderForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单编号" style="word-break: normal;">{{ orderForm.orderId }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单总金额">
              <template v-if="modifyConfig.amount.includes(orderForm.orderStatus)">
                <el-input-number placeholder="商品金额" style="width:140px" v-model="orderForm.orderAmount" controls-position="right" :min="0" :precision="2" :step="0.1"></el-input-number>
              </template>
              <template v-else>
                {{orderForm.orderAmount}}
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单总件数">{{ orderForm.productCounts }}件</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单状态">{{ orderForm.orderStatus | orderStateFilter(orderStateOptions) }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单日期">{{ orderForm.createTime | timeFilter }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新日期">{{ orderForm.updateTime | timeFilter }}</el-form-item>
          </el-col>
        </el-row>

        <!-- 商品列表 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>商品列表</span>
          </div>
          <el-table :border="true" :data="orderForm.orderItemDTOS">
            <el-table-column label="商品编号" prop="productCode" width="200"></el-table-column>
            <el-table-column label="商品名称" prop="productName"></el-table-column>
            <el-table-column label="商品价格" prop="productPrice" width="100"></el-table-column>
            <el-table-column label="商品数量" prop="productNum" width="100"></el-table-column>
            <el-table-column label="商品规格">
              <template slot-scope="scope">
                <div v-for="item in scope.row.properties" :key="item.id" class="properties-item">
                  {{ item.specName }}：<span v-for="row in item.properties" :key="row.id">{{ row.propertyName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column width="100" label="缩略图">
              <template slot-scope="scope">
                <img width="64" height="64" :src="scope.row.productPic" alt="">
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 配送信息 -->
        <el-card style="marginTop:20px" class="box-card">
          <div slot="header" class="clearfix">
            <span>配送信息</span>
          </div>
          <div class="content">
            <el-form-item label="选择快递">
              {{orderForm.deliveryDTO.deliveryName}}
              <!-- <el-select v-model="orderForm.deliveryDTO.deliveryName" placeholder="分类列表" disabled>
                <el-option v-for="item in deliveryOptions" :key="item.id" :label="item.deliveryName" :value="item.id"></el-option>
              </el-select> -->
            </el-form-item>
            <el-form-item label="快递单号">
              <template v-if="modifyConfig.delivery.includes(orderForm.orderStatus)">
                <el-input style="width:250px" v-model="orderForm.deliveryDTO.deliveryNo" placeholder="快递单号"></el-input>
              </template>
              <template v-else>
                {{orderForm.deliveryDTO.deliveryNo}}
              </template>
            </el-form-item>
          </div>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogOrderVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyOrder">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 安排配送 -->
    <el-dialog title="安排配送" v-if="dialogDeliveryVisible" :visible.sync="dialogDeliveryVisible" width="60%">
      <el-form :inline="false" label-width="100px" :model="deliveryForm" :rules="deliveryRules" ref="deliveryForm">
        <el-form-item label="配送地址">
          {{ deliveryForm.addressDTO | addressInfoFilter()}}
        </el-form-item>
        <el-form-item label="用户信息">
          {{ deliveryForm.addressDTO | customerInfoFilter()}}
        </el-form-item>
        <el-form-item label="快递公司">
          <el-select v-model="deliveryForm.deliveryName" placeholder="请选择">
            <el-option v-for="item in deliveryOptions" :key="item.id" :label="item.deliveryName" :value="item.deliveryName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop='deliveryNo'>
          <el-input v-model="deliveryForm.deliveryNo" placeholder="快递单号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDeliveryVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDeliveryInfo">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 物流信息 -->
    <el-dialog title="物流信息" v-if="expressInfo.visible" :visible.sync="expressInfo.visible" width="60%">
      <div class="express-container" v-if="expressInfo.logisticsList">
        <div class="title">
          <img :src="expressInfo.logo" />
          <span>{{expressInfo.expressName}}</span>
          <span>运单号：{{expressInfo.number}}</span>
        </div>
        <el-timeline class="list">
          <el-timeline-item v-for="(logistics, index) in expressInfo.logisticsList" :key="index" :timestamp="logistics.time">
            {{logistics.context}}
          </el-timeline-item>
        </el-timeline>
      </div>
      <div class="express-empty" v-else>{{expressInfo.isloading?'加载中...':'暂无数据'}}</div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import logisticsConfig from '../logistics/config';

export default {
  components: {},
  name: 'Category',
  data() {
    const nowTime = dayjs().format('YYYY-MM-DD');
    const agoTime = dayjs().subtract(7, 'day').format('YYYY-MM-DD');
    const defaultTime = [`${agoTime} 00:00:00`, `${nowTime} 23:59:59`];
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
      tableData: [],
      formData: {
        orderId: '', // 订单编号
        dateTime: defaultTime,
        orderState: '0' || this.$route.query.s, // 订单状态
      },
      orderStateOptions: [], // 订单状态选项

      // 分页设置
      currentPage: 1,
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0,

      // 修改订单弹窗
      dialogOrderVisible: false,
      orderForm: {},

      // 物流信息弹窗
      dialogDeliveryVisible: false,
      deliveryOptions: [],
      deliveryForm: {
        deliveryName: '',
        deliveryNo: '',
        orderId: '',
      },

      deliveryRules: {
        deliveryNo: [
          { required: true, message: '请输入快递单号', trigger: 'blur' },
        ],
      },

      // 快递信息
      expressInfo: {
        visible: false,
        isloading: true,
      },

      modifyConfig: {
        amount: [1, 2], // 修改金额
        delivery: [5, 7, 8], // 修改快递单号
      },
    };
  },
  mounted() {
    this.init();
  },
  filters: {
    orderStateFilter(keyValue, orderStateOptions) {
      if (orderStateOptions.length === 0) {
        return '';
      }
      return orderStateOptions.find((item) => +item.keyValue === +keyValue)
        .caption;
    },
    addressInfoFilter(addressDTO) {
      const { provinceName, addressDetail } = addressDTO || {};
      if (provinceName && addressDetail) {
        return `${provinceName} ${addressDetail}`;
      }
    },
    customerInfoFilter(addressDTO) {
      const { recevierName, receviePhone } = addressDTO || {};
      if (recevierName && receviePhone) {
        return `${recevierName} ${receviePhone}`;
      }
    },
  },
  methods: {
    init() {
      this.getOrderList();
      setTimeout(() => {
        this.getDicts();
        this.getDeliveries();
      }, 0);
    },
    // 获取订单列表
    async getOrderList(pageNum = 1) {
      this.pageNum = pageNum;
      const { pageSize, formData } = this.$data;

      if (!Array.isArray(formData.dateTime)) {
        this.$notify.warning({
          title: `温馨提示`,
          message: '请选择您要查询的时间段',
        });
        return;
      }

      const params = {
        pageNum,
        pageSize,
        orderId: formData.orderId,
        merchantId: this.$store.getters.customerId,
        orderStatus: formData.orderState,
        startTime: formData.dateTime[0],
        endTime: formData.dateTime[1],
      };
      if (params.orderStatus === '0') {
        delete params.orderStatus;
      }
      const response = await this.$api.getOrderList(params);
      // 自定义序号
      this.tableData = response.data;
      this.tableData.forEach((item, i) => {
        const o = item.orderStatus;
        item.order = (this.pageNum - 1) * this.pageSize + i + 1;
        // 按钮展示与否
        item.btnCancel = false;
        item.btnDelivery = [3].includes(o);
        item.btnReundAgree = [7, 8].includes(o);
        item.btnConfirmRemind = item.remind;
        item.btnGoodsTaked = [4].includes(o);
        item.btnExpress = !!item.deliveryNo;
        item.btnModify = [1, 2, 5, 7, 8].includes(o); // 1、2 修改金额 5、7、8 修改快递单号
      });

      this.pageTotal = response.total;
    },
    // 获取商家物流信息字典
    async getDeliveries() {
      const params = { type: logisticsConfig.deliveryType.Bound };
      const { data } = await this.$api.getDeliveries(params);
      this.deliveryOptions = data;
    },
    // 获取订单呢状态的数据字典
    async getDicts() {
      const { data } = await this.$api.getDicts({ keyNo: 1001 });
      this.orderStateOptions = data;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getOrderList(this.pageNum);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getOrderList(val);
    },
    handleSubmit() {
      this.getOrderList(this.pageNum);
    },
    // 修改订单
    async modifyOrder() {
      this.orderForm.merchantId = this.$store.getters.customerId;
      const { orderId, orderAmount, deliveryDTO } = this.orderForm;
      await this.$api.modifyOrder({
        orderId,
        orderAmount: +orderAmount,
        deliveryNo: deliveryDTO.deliveryNo,
      });
      this.$notify.success({ title: `更新成功`, message: '更新成功' });
      this.dialogOrderVisible = false;
      this.handleSubmit();
    },
    // 添加物流信息
    async addDeliveryInfo(row) {
      this.$refs.deliveryForm.validate(async (valid) => {
        if (valid) {
          const { orderId } = this.orderForm;
          console.log('orderId', orderId);
          // return;
          const params = {
            ...{},
            ...this.deliveryForm,
            ...{ orderId },
          };
          const response = await this.$api.deliveryOrder(params);
          if (response.success) {
            this.$notify.success({
              title: `配送成功`,
              message: '已经成功添加快递信息',
            });
            this.dialogDeliveryVisible = false;
            this.handleSubmit();
          }
        }
      });
    },
    // 取消订单
    async handleCancel(row) {
      this.orderForm = Object.assign({}, row);
      // const { id: deliveryId } = this.orderForm.deliveryDTO;
      const { orderId, deliveryId } = this.orderForm;
      await this.$api.modifyOrder({
        deliveryId,
        orderId,
        orderStatus: 7,
      });
      this.handleSubmit();
    },
    // 安排配送
    handleSend(row) {
      this.dialogDeliveryVisible = true;
      this.orderForm.orderId = row.orderId;
      this.deliveryForm = {
        ...this.deliveryForm,
        addressDTO: row.addressDTO,
      };
    },
    // 退款/货确认
    handleConfirmRefund(row) {
      this.$confirm('确认同意客户的退款/退货?', '提示')
        .then(() => {
          this.$api.confirmRefund(row.orderId).then((data) => {
            if (data.success) {
              this.$message('退款/退货成功~!');
              this.getOrderList(this.pageNum);
            }
          });
        })
        .catch(() => {});
    },
    // 知晓提醒
    handleConfirmRemind(row) {
      this.$api.ConfirmRemind(row.orderId).then((data) => {
        if (data.success) {
          this.$message('已确认收到提醒~!');
          this.getOrderList(this.pageNum);
        }
      });
    },
    // 货已自取
    handleGoodsTaked(row) {
      this.$confirm('确认自提货物已经领取?', '提示')
        .then(() => {
          this.$api.goodsTaked(row.orderId).then((data) => {
            if (data.success) {
              this.$message('货物自取成功');
              this.getOrderList(this.pageNum);
            }
          });
        })
        .catch(() => {});
    },
    // 安排修改订单
    handleModify(row) {
      if (row.deliveryDTO == null) row.deliveryDTO = {};
      this.orderForm = Object.assign({}, row);
      this.dialogOrderVisible = true;
    },
    // 物流信息
    async handleExpress(row) {
      this.expressInfo = { ...{}, ...{ visible: true, isloading: true } };
      const { success, data } = await this.$api.getExpressInfo({
        deliveryNo: row.deliveryNo,
      });
      if (success) {
        this.expressInfo = { ...this.expressInfo, ...data, isloading: false };
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .table-wrapper {
    margin-top: 20px;
  }
}

.table-wrapper /deep/ .el-table__expanded-cell[class*='cell'] {
  padding: 20px 10px;
}

.express-container {
  padding: 0 20px;
  max-height: 600px;
  overflow: scroll;

  img {
    width: 28px;
    height: 28px;
  }
  .title {
    height: 35px;
    line-height: 35px;
    font-weight: 700;
    display: flex;
    align-items: center;
    position: absolute;
    left: 0;
    right: 0;
    background-color: #fff;
    border-bottom: 1px solid #cdcdcd;
    z-index: 2;
    margin: 0 20px;
  }
  .title :first-child {
    margin-left: 5px;
  }
  .title :not(:first-child) {
    margin: 0 10px;
  }
  .list {
    margin-top: 50px;
    z-index: 1;
  }
}

.express-empty {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

::v-deep {
  .el-dialog__header {
    padding: 20px 20px 0 20px;
  }
  .el-dialog__body {
    padding: 0 10px;
  }
}
</style>
